<template>
  <div class="wpwork-common-layout">
    <div class="wpwork-common-layout-left">
      <div class="wpwork-common-title">
        <h2>群组分类</h2>
        <el-dropdown>
          <el-link icon="icon-ym icon-ym-mpMenu" :underline="false" />
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click.native="initData()">刷新数据</el-dropdown-item>
            <el-dropdown-item @click.native="toggleTreeExpand(true)">展开全部</el-dropdown-item>
            <el-dropdown-item @click.native="toggleTreeExpand(false)">折叠全部</el-dropdown-item>
<!--            <el-dropdown-item @click.native="handleTypeManage">分类管理</el-dropdown-item>-->
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="wpwork-common-tree-search-box">
        <el-input placeholder="输入关键字" v-model="filterText" suffix-icon="el-icon-search" clearable />
      </div>
      <el-scrollbar class="wpwork-common-el-tree-scrollbar" v-loading="treeLoading">
        <el-tree ref="treeBox" :data="treeData" :props="defaultProps"
                 :default-expand-all="expandsTree" highlight-current :expand-on-click-node="false"
                 node-key="id" @node-click="handleNodeClick" class="wpwork-common-el-tree"
                 :filter-node-method="filterNode" v-if="refreshTree" :render-after-expand="false"
                 empty-text="暂无分组数据">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <i class="el-icon-folder" />
            <span class="text">{{ node.label }}</span>
          </span>
        </el-tree>
      </el-scrollbar>
    </div>
    <div class="wpwork-common-layout-center">
<!--      <el-row class="wpwork-common-search-box" :gutter="16">-->
<!--        <el-form @submit.native.prevent>-->
<!--&lt;!&ndash;          <el-col :span="6">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-form-item label="关键词">&ndash;&gt;-->
<!--&lt;!&ndash;              <el-input v-model="listQuery.keyword" placeholder="请输入关键词查询" clearable&ndash;&gt;-->
<!--&lt;!&ndash;                        @keyup.enter.native="search()" />&ndash;&gt;-->
<!--&lt;!&ndash;            </el-form-item>&ndash;&gt;-->
<!--&lt;!&ndash;          </el-col>&ndash;&gt;-->
<!--          <el-col :span="6">-->
<!--            <el-form-item>-->
<!--&lt;!&ndash;              <el-button type="primary" icon="el-icon-search" @click="search()">&ndash;&gt;-->
<!--&lt;!&ndash;                {{$t('common.search')}}</el-button>&ndash;&gt;-->
<!--              <el-button icon="el-icon-refresh-right" @click="reset()">{{$t('common.reset')}}-->
<!--              </el-button>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-form>-->
<!--      </el-row>-->
      <div class="wpwork-common-layout-main wpwork-flex-main">
        <div class="wpwork-common-head">
          <div class="wpwork-common-head-right">
            <el-tooltip effect="dark" content="展开" placement="top"
                        v-if="tableData.length&&tableData.every((item)=>{return item.hasChildren})">
              <el-link v-show="!expands" type="text"
                       icon="icon-ym icon-ym-btn-expand wpwork-common-head-icon" :underline="false"
                       @click="toggleExpand()" />
            </el-tooltip>
            <el-tooltip effect="dark" content="折叠" placement="top"
                        v-if="tableData.length&&tableData.every((item)=>{return item.hasChildren})">
              <el-link v-show="expands" type="text"
                       icon="icon-ym icon-ym-btn-collapse wpwork-common-head-icon" :underline="false"
                       @click="toggleExpand()" />
            </el-tooltip>
            <el-tooltip effect="dark" :content="$t('common.refresh')" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh wpwork-common-head-icon" :underline="false"
                       @click="initData()" />
            </el-tooltip>
          </div>
        </div>

        <!-- 右侧表单内容 -->
        <div style="width: 700px;margin-left: 30px;">
          <el-form ref="dataFrom" v-loading="formLoading" :model="dataFrom"
                   class="menuForm" style="width: 500px;" label-width="100px" :rules="formRules">
            <wpwork-form-tip-item label="群组名称" prop="name">
              <el-input v-model="dataFrom.name" placeholder="请输入群组名称" clearable />
            </wpwork-form-tip-item>
            <wpwork-form-tip-item label="群组编码" prop="code">
              <el-input v-model="dataFrom.code" placeholder="请输入群组编码" clearable />
            </wpwork-form-tip-item>
            <wpwork-form-tip-item label="父群组">
              <el-input v-model="dataFrom.parentName" disabled />
            </wpwork-form-tip-item>
            <wpwork-form-tip-item label="群组描述">
              <el-input
                type="textarea"
                v-model="dataFrom.description"
                placeholder="请输入群组描述"
                :rows="3"
                clearable
              />
            </wpwork-form-tip-item>
            <wpwork-form-tip-item label="排序">
              <el-input-number v-model="dataFrom.sortOrder" :min="0" :max="999" />
            </wpwork-form-tip-item>
          </el-form>

          <div style="margin-top: 20px;">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">提交</el-button>
            <el-button type="danger" @click="deleteGroup" :disabled="!dataFrom.id">删除</el-button>
            <el-button type="primary" @click="createSubGroup" :disabled="!dataFrom.id">创建子群</el-button>
            <el-button type="primary" @click="openBindUsersDialog" :disabled="!dataFrom.id">绑定用户</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 绑定用户对话框 -->
    <el-dialog
      title="绑定用户"
      :visible.sync="bindUsersDialog"
      width="50%"
      @close="handleBindDialogClose"
    >
      <div class="user-bind-panel">
        <el-transfer
          v-model="selectedUsers"
          :data="userList"
          :titles="['所有用户', '已绑定用户']"
          :props="{
            key: 'id',
            label: 'name'
          }"
          filterable
          :filter-method="filterMethod"
          filter-placeholder="请输入用户名搜索"
        />

        <div style="margin-top: 20px; text-align: center;">
          <el-button type="primary" @click="saveBinding" :loading="bindLoading">保存绑定</el-button>
          <el-button @click="bindUsersDialog = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <Form v-if="formVisible" ref="Form" @refreshDataList="getDictionaryList" />
    <TypeList v-if="drawer" ref="TypeList" @refreshDataList="initData" />
    <!-- 在主组件的模板中添加 -->
    <UserBindDialog
      v-if="userBindDialogVisible"
      ref="userBindDialog"
      @success="handleBindSuccess"
    />
  </div>
</template>

<script>
import {
  getDictionaryType,
  getDictionaryDataList,
  delDictionaryData,
  updateDictionaryState
} from '@/api/systemData/dictionary'
import Form from './Form'
import TypeList from './components/index'
import UserBindDialog from './components/UserBindPanel.vue'
import { getTree, createGroup, updateGroup, deleteGroup, getGroupUsers, bindUsers, unbindUsers } from '@/api/group'

export default {
  name: 'systemData-dictionary',
  components: {
    Form,
    TypeList,
    UserBindDialog
  },
  data() {
    return {
      // 表单验证规则
      formRules: {
        name: [
          { required: true, message: '请输入群组名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入群组编码', trigger: 'blur' }
        ]
      },
      // 绑定用户相关
      userBindDialogVisible: false,
      bindUsersDialog: false,
      bindLoading: false,
      selectedUsers: [],
      userList: [],
      // 提交加载状态
      submitLoading: false,
      formLoading: false,
      // 表单数据
      dataFrom: {
        id: null,
        name: '',
        code: '',
        parentId: null,
        parentName: '',
        description: '',
        sortOrder: 0
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      listQuery: {
        keyword: '',
        isTree: 0
      },
      typeId: '',
      drawer: false,
      formVisible: false,
      treeLoading: false,
      listLoading: false,
      treeData: [],
      tableData: [],
      expands: true,
      expandsTree: true,
      refreshTable: true,
      refreshTree: true,
      filterText: '',
      // 当前选中的节点
      currentNode: null
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeBox && this.$refs.treeBox.filter(val)
    }
  },
  created() {
    this.initData(true)
  },
  methods: {
    search() {
      // 搜索功能
      console.log('搜索:', this.listQuery.keyword)
    },
    reset() {
      this.listQuery.keyword = ''
    },
    // 修改 initData 方法，移除默认选择第一个节点的逻辑
    initData(isInit) {
      this.filterText = ''
      this.treeLoading = true

      console.log('开始获取树形数据...')

      getTree().then(res => {
        console.log('完整响应:', res)
        console.log('响应数据data字段:', res.data)

        // 根据你的接口返回结构调整
        let treeData = []

        if (res.data && res.data.code === 200) {
          treeData = res.data.data
          console.log('使用 res.data.data:', treeData)
        }
        else if (Array.isArray(res.data)) {
          treeData = res.data
          console.log('使用 res.data (数组):', treeData)
        }
        else if (res.data && Array.isArray(res.data)) {
          treeData = res.data
          console.log('使用 res.data (直接数组):', treeData)
        }
        else {
          treeData = res.data || []
          console.log('使用默认 res.data:', treeData)
        }

        console.log('最终treeData:', treeData)

        // 设置树形数据
        this.treeData = treeData

        this.$nextTick(() => {
          // 移除了默认选择第一个节点的逻辑，现在不会自动选择任何节点
          this.treeLoading = false
          console.log('树形数据加载完成')
        })
      }).catch(error => {
        console.error('获取树形数据失败:', error)
        this.treeLoading = false
        this.$message.error('加载分组数据失败')
      })
    },

    // 过滤树节点
    filterNode(value, data) {
      if (!value) return true;
      // 根据实际数据字段调整
      return data.name && data.name.indexOf(value) !== -1;
    },
    toggleExpand() {
      this.refreshTable = false;
      this.expands = !this.expands;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    // 切换树展开状态
    toggleTreeExpand(expands) {
      this.filterText = ''
      this.refreshTree = false
      this.expandsTree = expands
      this.$nextTick(() => {
        this.refreshTree = true
        this.$nextTick(() => {
          if (this.typeId && this.$refs.treeBox) {
            this.$refs.treeBox.setCurrentKey(this.typeId)
          }
        })
      })
    },
    getDictionaryList() {
      console.log("获取字典列表")
      this.listLoading = true
      getDictionaryDataList(this.typeId, this.listQuery).then(res => {
        this.tableData = res.data.list
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 分类管理
    handleTypeManage() {
      this.drawer = true
      this.$nextTick(() => {
        this.$refs.TypeList && this.$refs.TypeList.init()
      })
    },
    // 节点点击事件 - 修复版本
    handleNodeClick(data) {
      console.log("点击节点数据:", data)

      if (!data || !data.id) {
        console.warn('节点数据无效:', data)
        return
      }

      if (this.typeId === data.id) return

      this.typeId = data.id
      this.currentNode = data

      // 填充表单数据 - 根据实际数据字段调整
      this.dataFrom = {
        id: data.id,
        name: data.name || '',
        code: data.code || '',
        parentId: data.parentId || null,
        parentName: data.parentName || '根分组',
        description: data.description || '',
        sortOrder: data.sortOrder || 0
      }

      console.log('表单数据已更新:', this.dataFrom)
    },
    // 创建子群组
    createSubGroup() {
      if (!this.currentNode) {
        this.$message.warning('请先选择一个群组')
        return
      }

      // 重置表单，准备创建子群组
      this.dataFrom = {
        id: null,
        name: '',
        code: '',
        parentId: this.currentNode.id,
        parentName: this.currentNode.name || '未知分组',
        description: '',
        sortOrder: 0
      }

      this.$message.info('请填写子群组信息后点击提交')
    },
    // 提交表单（创建或更新）
    submitForm() {
      this.$refs.dataFrom.validate((valid) => {
        if (!valid) {
          this.$message.warning('请完善表单信息')
          return
        }

        this.submitLoading = true

        // 准备提交数据
        const submitData = {
          name: this.dataFrom.name,
          code: this.dataFrom.code,
          parentId: this.dataFrom.parentId,
          description: this.dataFrom.description,
          sortOrder: this.dataFrom.sortOrder || 0
        }

        console.log('提交数据:', submitData)

        const request = this.dataFrom.id ?
          updateGroup(this.dataFrom.id, submitData) :
          createGroup(submitData)

        request.then(res => {
          console.log('提交响应:', res)
          if (res.code === 200) {
            this.$message.success(this.dataFrom.id ? '更新成功' : '创建成功')
            this.initData(false) // 刷新树形数据
            // 如果是创建操作，清空表单
            if (!this.dataFrom.id) {
              this.resetForm()
            }
          } else {
            this.$message.error(res.data.msg || '操作失败')
          }
        }).catch(error => {
          console.error('提交失败:', error)
          this.$message.error('操作失败: ' + (error.message || '未知错误'))
        }).finally(() => {
          this.submitLoading = false
        })
      })
    },
    // 删除群组
    deleteGroup() {
      if (!this.dataFrom.id) {
        this.$message.warning('请选择要删除的群组')
        return
      }

      this.$confirm('确定删除该群组吗？删除后无法恢复', '提示', {
        type: 'warning'
      }).then(() => {
        deleteGroup(this.dataFrom.id).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.initData(false) // 刷新树形数据
            this.resetForm()
          } else {
            this.$message.error(res.data.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除失败:', error)
          this.$message.error('删除失败: ' + (error.message || '未知错误'))
        })
      }).catch(() => {
        // 用户取消删除
      })
    },
    // 重置表单
    resetForm() {
      this.dataFrom = {
        id: null,
        name: '',
        code: '',
        parentId: null,
        parentName: '',
        description: '',
        sortOrder: 0
      }
      this.$refs.dataFrom && this.$refs.dataFrom.clearValidate()
    },
    // 绑定用户相关方法
    filterMethod(query, item) {
      return item.name && item.name.indexOf(query) > -1
    },
    // 处理绑定用户对话框关闭
    handleBindDialogClose() {
      this.bindUsersDialog = false
      this.selectedUsers = []
    },
    // 打开绑定用户对话框
    openBindUsersDialog() {
      if (!this.dataFrom.id) {
        this.$message.warning('请先选择一个群组')
        return
      }

      this.userBindDialogVisible = true
      this.$nextTick(() => {
        this.$refs.userBindDialog.init(this.dataFrom.id, this.dataFrom.name)
      })
    },

    handleBindSuccess() {
      this.userBindDialogVisible = false
      // this.$message.success('绑定用户操作成功')
      // 可以在这里刷新其他相关数据
    },

    // 加载用户数据
    async loadUserData() {
      try {
        // 模拟用户数据
        this.userList = [
          {id: 1, name: '用户1'},
          {id: 2, name: '用户2'},
          {id: 3, name: '用户3'},
          {id: 4, name: '用户4'},
          {id: 5, name: '用户5'}
        ]

        // 加载已绑定的用户
        if (this.dataFrom.id) {
          const response = await getGroupUsers(this.dataFrom.id)
          if (response.data.code === 200) {
            this.selectedUsers = response.data.data
          }
        }
      } catch (error) {
        this.$message.error('加载用户数据失败')
      }
    },
    // 保存绑定
    async saveBinding() {
      if (!this.dataFrom.id) {
        this.$message.warning('请先选择分组')
        return
      }

      this.bindLoading = true
      try {
        // 获取当前已绑定的用户
        const currentUsers = await getGroupUsers(this.dataFrom.id)
        const currentUserIds = currentUsers.data.data || []

        // 计算需要解绑的用户
        const unbindUserIds = currentUserIds.filter(id => !this.selectedUsers.includes(id))

        // 计算需要绑定的用户
        const bindUserIds = this.selectedUsers.filter(id => !currentUserIds.includes(id))

        // 执行解绑和绑定操作
        if (unbindUserIds.length > 0) {
          await unbindUsers(this.dataFrom.id, unbindUserIds)
        }

        if (bindUserIds.length > 0) {
          await bindUsers(this.dataFrom.id, bindUserIds)
        }

        this.$message.success('绑定用户成功')
        this.bindUsersDialog = false
      } catch (error) {
        this.$message.error('绑定用户失败')
        console.error('绑定用户失败:', error)
      } finally {
        this.bindLoading = false
      }
    },
    // 其他原有方法...
    handleUpdateState(row) {
      const txt = row.enabledMark ? '禁用' : '开启'
      this.$confirm(`您确定要${txt}当前数据吗, 是否继续?`, '提示', {
        type: 'warning'
      }).then(() => {
        updateDictionaryState(row.id).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            duration: 1000,
            onClose: () => {
              this.$store.commit('base/SET_DICTIONARY_LIST', [])
              row.enabledMark = row.enabledMark ? 0 : 1
            }
          })
        })
      }).catch(() => {
      })
    },
    addOrUpdateHandle(id) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.Form && this.$refs.Form.init(id, this.typeId, this.listQuery.isTree)
      })
    },
    handleDel(id) {
      this.$confirm(this.$t('common.delTip'), this.$t('common.tipTitle'), {
        type: 'warning'
      }).then(() => {
        delDictionaryData(id).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            duration: 1500,
            onClose: () => {
              this.$store.commit('base/SET_DICTIONARY_LIST', [])
              this.getDictionaryList()
            }
          })
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped>
.user-bind-panel {
  padding: 10px;
}
</style>
